import socketserver
import os
import re
import json
import struct
from optparse import OptionParser


# 接受头部信息
def sendFile(conn, head_info, head_info_len, filename):
    try:
        conn.send(head_info_len)
        conn.send(head_info.encode('utf-8'))
        with open(filename, 'rb') as f:
            conn.sendall(f.read())
        print('[+]send success! ' + filename)
    except:
        print('[-]send fail! ' + filename)


# 获取原来的文件名
def operafile(filename):
    filesize = os.path.getsize(filename)
    pattern = re.compile(r'([^<>/\\\|:""\*\?]+\.\w+$)')
    data = pattern.findall(filename)
    head_dir = {
        'filename': data,
        'filesize': filesize
    }
    head_info = json.dumps(head_dir)
    head_info_len = struct.pack('i', len(head_info))
    return head_info_len, head_info


class Mysever(socketserver.BaseRequestHandler):
    buffsize = 1024

    def handle(self):
        print('[client ip is]:', self.client_address[0], '\n')
        while True:
            filename = input('Please enter the file name to be sent >>>'.split())
            if (filename == 'exit'):
                break
            head_info_len, head_info = operafile(filename)
            sendFile(self.request, head_info, head_info_len, filename)
        self.request.close()


def main():
    parser = OptionParser("Usage:%prog -p <port>")
    parser.add_option('-p', type='string', dest='port', help='input port')
    options, args = parser.parse_args()
    t_port = int(options.port)
    print(t_port)

    s = socketserver.ThreadingTCPServer(('127.0.0.1,port'), Mysever)
    s.serve_forever()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('error')
